package com.example.springcloudwinter.service;

import com.example.springcloudwinter.bo.OrderBo;
import com.example.springcloudwinter.dto.ResultEntity;
import com.example.springcloudwinter.feign.OrderFeignClient;
import com.example.springcloudwinter.mapper.PointMapper;
import com.example.springcloudwinter.po.OrderPo;
import com.example.springcloudwinter.po.PointPo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.SQLException;
import java.util.List;

@Service
public class PointService {
    private static final int MAX_POINT = 500;

    @Autowired
    private PointMapper pointsMapper;
    @Autowired
    private OrderFeignClient orderFeignClient;

    public ResultEntity<?> listPoints (String userId){
        ResultEntity<List<PointPo>> result=new ResultEntity<>();
        try {
            List<PointPo> pointsList = pointsMapper.listPoints(userId);
            result.setDetail(pointsList).setCode(200);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return result;
    }

    public ResultEntity<?> payPoint (OrderPo orderPo,String userId) throws SQLException {
            int points = 0;
            // 限定积分使用最大值不能超出订单上限
            List<OrderBo> validPoints;
            validPoints = pointsMapper.getValidPoints(userId);
            double max = MAX_POINT > orderPo.getOrderTotal()*100 ? MAX_POINT : orderPo.getOrderTotal()*100;
            for (OrderBo orderEntity : validPoints) {
                points += orderEntity.getRemainingPoints();
                if (points >= MAX_POINT) {
                    orderEntity.setRemainingPoints(points - MAX_POINT);
                    pointsMapper.updatePoints(orderEntity.getOrderId(), orderEntity.getRemainingPoints());
                    break;
                }
                else {
                    pointsMapper.updatePoints(orderEntity.getOrderId(), 0);
                }
            }
        return new ResultEntity<>();
    }
}

